package z.sftpd;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.UserAuthNoneFactory;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.shell.InteractiveProcessShellFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

public class MyService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
        var path = getExternalFilesDir(null).getAbsolutePath();
        new Thread(()->{
            System.setProperty("user.home",path);
            var sshd = SshServer.setUpDefaultServer();
            sshd.setPort(2222);
            sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get(path, "key")));
            sshd.setUserAuthFactories(List.of(new UserAuthNoneFactory()));
            sshd.setSubsystemFactories(List.of(new SftpSubsystemFactory()));
            sshd.setFileSystemFactory(new VirtualFileSystemFactory(Paths.get("/sdcard")));
            sshd.setShellFactory(InteractiveProcessShellFactory.INSTANCE);
            try {
                sshd.start();
                synchronized (MyService.class) {
                    MyService.class.wait();
                }
            } catch (IOException | InterruptedException e) {
            }
        }).start();

        var b = new Notification.Builder(this,"1");
        b.setContentIntent(PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0));
        b.setAutoCancel(false);
        startForeground(1, b.build());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }
}